// API基础URL
const API_BASE_URL = 'http://localhost';
// 登录页面DOM加载完成时
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('loginForm')
        .addEventListener('submit', function(e) {
            e.preventDefault();
            handleLogin();
        });
});

async function handleLogin() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const rememberMe = document.getElementById('rememberMe').checked;
    
    // 简单验证
    if (!username || !password) {
        showToast('请输入用户名和密码', 'error');
        return;
    }
    
    // 显示加载状态
    const loginBtn = document.getElementById('loginBtn');
    const originalBtnHtml = loginBtn.innerHTML;
    loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> 登录中...';
    loginBtn.disabled = true;
    
    try {
        // 使用表单方式调用登录API
        const response = await submitLoginForm(username, password, rememberMe);
        if (response.ok) {

            // 保存登录状态
            localStorage.setItem('user', 'true');
            if (rememberMe) {
                localStorage.setItem('rememberMe', 'true');
                localStorage.setItem('username', username);
            } else {
                localStorage.removeItem('rememberMe');
                localStorage.removeItem('username');
            }
            
            showToast('登录成功', 'success');

            window.location.href = 'user.html';
        } else {
            // 尝试从响应中获取错误信息
            const errorData = await response.json();
            showToast(errorData.message || errorData.data || '登录失败', 'error');
        }
    } catch (error) {
        console.error('Login error:', error);
        showToast('登录过程中发生错误: ' + error.message, 'error');
    } finally {
        // 恢复按钮状态
        loginBtn.innerHTML = originalBtnHtml;
        loginBtn.disabled = false;
    }
}

// 使用表单方式提交登录请求
async function submitLoginForm(username, password, rememberMe) {
    // 创建表单数据
    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);
    formData.append('rememberMe', rememberMe);

    return await fetch(`${API_BASE_URL}/api/rest/user/login`, {
        method: 'POST',
        body: formData,
    });
}

function showToast(message, type) {
    const backgroundColor = type === 'success' 
        ? "linear-gradient(to right, #00b09b, #96c93d)"
        : "linear-gradient(to right, #ff5f6d, #ffc371)";
        
    Toastify({
        text: message,
        duration: 3000,
        close: true,
        gravity: "top",
        position: "right",
        backgroundColor: backgroundColor,
        style: {
            borderRadius: "10px"
        }
    }).showToast();
}

// 页面加载时检查是否记住用户名
window.addEventListener('load', function() {
    if (localStorage.getItem('rememberMe') === 'true') {
        const savedUsername = localStorage.getItem('username');
        if (savedUsername) {
            document.getElementById('username').value = savedUsername;
            document.getElementById('rememberMe').checked = true;
        }
    }
});